package com.songqintuan.mall.customer;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Map;
import java.util.UUID;

import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.servlet.http.HttpServletRequest;

import org.richfaces.event.FileUploadEvent;
import org.richfaces.model.UploadedFile;

import com.songqintuan.common.bean.UploadedImage;
import com.songqintuan.common.util.SpringFacesUtil;

/**
 * @author Ilya Shaikovsky
 */
@ManagedBean(name = "customerFileUpload")
@SessionScoped
public class CustomerFileUploadBean implements Serializable {
	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	private ArrayList<UploadedImage> files = new ArrayList<UploadedImage>();
	private int uploadsAvailable = 5;
	private boolean autoUpload = false;
	private boolean useFlash = false;

	public int getUploadsAvailable() {
		return uploadsAvailable;
	}

	public void setUploadsAvailable(int uploadsAvailable) {
		this.uploadsAvailable = uploadsAvailable;
	}

	public boolean isAutoUpload() {
		return autoUpload;
	}

	public void setAutoUpload(boolean autoUpload) {
		this.autoUpload = autoUpload;
	}

	public boolean isUseFlash() {
		return useFlash;
	}

	public void setUseFlash(boolean useFlash) {
		this.useFlash = useFlash;
	}

	public void paint(OutputStream stream, Object object) throws IOException {
		stream.write(getFiles().get((Integer) object).getData());
		stream.close();
	}

	public void listener(FileUploadEvent event) throws Exception {
		UploadedFile item = event.getUploadedFile();
		UploadedImage file = new UploadedImage();
		file.setLength(item.getData().length);
		file.setName(item.getName());
		file.setData(item.getData());
		files.add(file);
		uploadsAvailable--;
		UIComponent component = event.getComponent();      
        Map<String, Object> map = component.getAttributes();      
        String projectNo = ((String)map.get("projectNo")); 
		// 将图片保存到应用程序的包根目录下
		FacesContext objContext = SpringFacesUtil.getFacesContext()
				.getCurrentInstance();
		HttpServletRequest request = (HttpServletRequest) objContext
				.getExternalContext().getRequest();
		String filePath = request.getSession().getServletContext()
				.getRealPath("/") + "resources/uploadfiles/projectNo/" + projectNo + "/";
		File out = new File(filePath);
	    if(!out.exists()){
	     //如果文件夹未创建就新建
	     out.mkdirs();
	    }
		String extension = "";
		int extDot = item.getName().lastIndexOf('.');
		if (extDot > 0) {
			extension = (item.getName()).substring(extDot + 1);
		}
		String fileName = UUID.randomUUID().toString() + "." + extension;
		java.io.File saveFile = new java.io.File(filePath, fileName);
		BufferedInputStream fis = null;
		BufferedOutputStream bos = null;
		int bytes = 0;
		byte[] bteFile = new byte[1024];
		try {
			fis = new BufferedInputStream(item.getInputStream());
			bos = new BufferedOutputStream(new FileOutputStream(saveFile));
			while ((bytes = fis.read(bteFile)) != -1) {
				bos.write(bteFile, 0, bytes);
			}
			bos.flush();
		} catch (IOException ioe) {
			ioe.printStackTrace();

			// uploadResult.put("success", new Boolean(false));
			// uploadResult.put("errorMessage", "上传文件失败");
			// return uploadResult;
		} catch (Exception e) {
			e.printStackTrace();
			// logger.error(ExceptionUtil.getStackTraceMessage(e));
			// uploadResult.put("success", new Boolean(false));
			// uploadResult.put("errorMessage", "上传文件失败");
			// return uploadResult;
		} finally {
			try {
				// 关闭输出流
				if (bos != null) {
					bos.close();
				}
				// 关闭输入流
				if (fis != null) {
					fis.close();
				}
			} catch (IOException ioe) {
				ioe.printStackTrace();
				// logger.error(ExceptionUtil.getStackTraceMessage(ioe));
			}
		}
	}

	public String clearUploadData() {
		files.clear();
		setUploadsAvailable(5);
		return null;
	}

	public int getSize() {
		if (getFiles().size() > 0) {
			return getFiles().size();
		} else {
			return 0;
		}
	}

	public long getTimeStamp() {
		return System.currentTimeMillis();
	}

	public ArrayList<UploadedImage> getFiles() {
		return files;
	}

	public void setFiles(ArrayList<UploadedImage> files) {
		this.files = files;
	}
}
